/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.ai.api.service;

import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.pgvector.PgVectorEmbeddingStore;
import java.util.Objects;
import org.elsfs.cloud.module.ai.api.entity.AiEmbeddingStore;
import org.elsfs.cloud.module.ai.api.enums.StoreType;

/** Embedding store service interface. */
public interface AiEmbeddingStoreService {

  /**
   * Retrieves an embedding store containing text segments for the specified store ID.
   *
   * @param storeId the unique identifier of the embedding store to retrieve
   * @return an instance of {@code EmbeddingStore<TextSegment>} associated with the given store ID
   */
  EmbeddingStore<TextSegment> getEmbeddingStoreByStoreId(String storeId);

  /**
   * Retrieves an embedding store containing text segments based on the provided configuration
   * details.
   *
   * @param aiEmbeddingStore the configuration details of the embedding store to retrieve
   * @return an instance of {@code EmbeddingStore<TextSegment>} constructed using the provided
   *     configuration
   */
  default EmbeddingStore<TextSegment> getEmbeddingStore(AiEmbeddingStore aiEmbeddingStore) {
    final var storetype = StoreType.getByCode(aiEmbeddingStore.getStoreType());
    if (StoreType.PGVector.equals(storetype)) {
      return buildPgVector(aiEmbeddingStore);
    }
    return null;
  }

  private PgVectorEmbeddingStore buildPgVector(AiEmbeddingStore store) {
    final var storeBuilder = PgVectorEmbeddingStore.builder();
    if (Objects.equals("0", store.getConfType())) {
      final var split = store.getApiKey().split(":");
      storeBuilder
          .createTable(true)
          .dropTableFirst(true)
          .host(store.getHost())
          .port(store.getPort())
          .user(split[0])
          .password(split[1])
          .database(store.getExtData())
          .table(store.getExtData())
          .dimension(384)
          .build();
      storeBuilder.createTable(true);
    }
    return storeBuilder.build();
  }
}
